package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"inventory-system/appconfig"
)

var Db *gorm.DB
var err error

func Init() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	data := appconfig.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		data.User,
		data.Password,
		data.Host,
		data.Port,
		data.Data,
	)
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库链接失败")
	} else {
		fmt.Println("数据库链接成功")
	}
	err = Db.AutoMigrate(&User{}, Product{})
	if err != nil {
		fmt.Println("迁移失败")
	} else {
		fmt.Println("迁移成功")
	}
}
